<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-row class="el-top">
        <el-col :span="4">
          <el-form-item class="ml20 mt8 mr20" label="出库方式:" prop="exportClass">
            <el-select v-model="form.exportClass" placeholder="请选择出库方式" @change="exportClassClick">
              <el-option v-for="(dict, index) in typeList" :key="dict.dictValue" :label="dict.dictLabel"
                         :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item class="mt8" label="供货单位:" prop="storageId">
            <drug-storage-dept ref="drugStorageDeptRef" :org-id="queryParams.orgId" :value="form.storageId"
                               :value-storage-id="form.storageId" class="import-master" style="width: 180px"
                               disabled="disabled" @drugStorageChange="storageIdClick"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item v-if="form.exportClass === '8'" class="mt8" label="退货单位:" prop="receiverSupplierRef">
            <supplier :id="form.receiverSupplier" ref="receiverSupplierRef" :placeholder="'请选择退货单位'"
                      style="float: left; width: 180px"
                      @supplierChange="receiverSupplierChange"/>
          </el-form-item>
          <el-form-item v-else-if="form.exportClass !== '9'" class="mt8" label="接收科室:" prop="receiverSupplier">
            <drug-storage-info ref="receiverIdDeptRef" :drug-fromLevel-str="drugFromLevelStr" :org-id="queryParams.orgId"
                               :value="defaultReceiverIdValue" :value-storage-id="currentSelectDept"
                               class="import-master" style="width: 180px"
                               @drugStorageChange="receiverIdClick"/>
          </el-form-item>
        </el-col>
        <span class="el-form-item__label ml10 mt5">进价合计：<span class="fz19 font-color-red mr5"> {{
            tradePriceTotal
          }}</span>元</span>
        <span class="el-form-item__label ml10 mt5">售价合计：<span class="fz19 font-color-red mr5"> {{
            retailPriceTotal
          }}</span>元</span>
      </el-row>
      <el-row>
        <!-- 出库编辑列表 -->
        <el-table :border="true" :data="form.detailList" :header-cell-style="$headerCellStyle"
                  header-cell-class-name="requiredClass">
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="168px" prop="drugName">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.itemInfo'" :rules="rules.itemInfo"
                            class="table-form-margin">
                <!-- 出库药品检索 -->
                <el-input v-if="scope.row.isShow" v-model="scope.row.drugName"
                          @focus="isShowItemNameFocus(scope.$index, scope.row)">
                </el-input>
                <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                                      :table-head-list="tableHeadList" :title="itemTitle"
                                      :width="1230"
                                      style="width: 100%" @itemNameInput="itemNameInput"
                                      @rowClick="rowClick($event, 0)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价(元)" prop="tradePrice"
                           width="100px">
            <template #default="scope">
              {{ scope.row.tradePrice }}
              <!-- <el-form-item :prop="'detailList.' + scope.$index + '.tradePrice'" :rules="rules.tradePrice"
  class="table-form-margin">
  <el-input v-model="scope.row.tradePrice" @blur="tradePriceBlue(scope.$index)"></el-input>
</el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                           width="90px">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['price_ratio']" :value="scope.row.discount"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价(元)" prop="retailPrice"
                           width="100px">
            <template #default="scope">
              {{ scope.row.retailPrice }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                           width="120px">
            <template #default="scope">
              {{ scope.row.batchNo }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库数量" prop="quantity"
                           width="140px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.quantity'" :rules="rules.quantity"
                            class="table-form-margin">
                <el-input v-model="scope.row.quantity">
                  <template #append>
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.currentUnits"/>
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="160px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="130px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注"
                           width="140px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.remarks'"
                            class="table-form-margin">
                <el-input v-model="scope.row.remarks" :rows="1" type="textarea"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作" width="70px">
            <template #default="scope">
              <el-tooltip class="item" content="添加" effect="dark" placement="top">
                <el-button circle type="primary" @click="handleAdd">
                  <template #icon>
                    <i-ep-plus/>
                  </template>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="mt5 mb5">
          <span class="mb-10">待出库药品</span>
          <span class="ml10">
            <el-button type="success" @click="lastSave"><template #icon>
                    <i-ep-FolderOpened/>
                </template>保存
            </el-button>
          </span>
          <span class="ml10">
            <el-button :disabled="buttonLoading" type="info" @click="temporaryStorageTableClick">
              <template #icon>
                <i-ep-memo/>
              </template>
              撤销列表
            </el-button>
          </span>
        </div>
        <el-table v-adaptive="110" :border="true" :data="form.detailListSave" :header-cell-style="$headerCellStyle"
                  highlight-current-row>
          <el-table-column :align="'center'" label="序号" min-width="45px" prop="index">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="168px" prop="drugName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价(元)" prop="tradePrice"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价(元)" prop="retailPrice"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库数量" prop="quantity"
                           width="90px">
            <template #default="scope">
              <div>
                <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.currentUnits"
                               class="mb-10 mr10" style="float: right"/>
                <div class="mr20" style="float: right; font-weight: bold">
                  {{ scope.row.quantity }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                           width="140px">
            <template #default="scope">
              <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="160px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="120px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="100px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="80px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注" prop="remarks"
                           width="80px"/>
          <el-table-column :align="'right'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作" width="100px">
            <template #default="scope">
              <el-tooltip class="item" content="编辑" effect="dark" placement="top">
                <el-button v-hasPerm="['base:drugImportMaster:edit']" circle type="success"
                           @click="handleUpdate(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip circle class="item" content="删除" effect="dark" placement="top">
                <el-button v-hasPerm="['base:drugImportMaster:remove']" circle type="danger"
                           @click="handleDelete(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="'撤销列表'" append-to-body width="94%"
               @close="temporaryStorageClose">
        <el-row :gutter="10">
        <el-col :span="10">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>主记录（点击列表可查看出库药品明细）</span>
            </div>
            <div class="mb20">
              <el-table :border="true" :data="stagingList" :header-cell-style="$headerCellStyle" height="400"
                         @row-click="stagingMaster">
                <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="left"
                        header-align="center" label="操作" width="80px">
                  <template #default="scope">
                    <el-tooltip class="item" content="引入"
                                effect="dark"
                                placement="top">
                      <el-button circle type="primary" @click.stop="bringIn(scope.row)">
                        <template #icon>
                          <i-ep-edit/>
                        </template>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip class="item" content="删除"
                                effect="dark"
                                placement="top">
                      <el-button circle type="danger" @click.stop="deleteMaster(scope.row)">
                        <template #icon>
                          <i-ep-delete/>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库类别"
                                   min-width="80px" prop="exportClass">
                    <template #default="scope">
                      <dict-data-tag :options="dictDataMap['drug_storage_type']"
                                     :value="scope.row.exportClass"/>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库单号"
                                   min-width="120px" prop="documentNo" width=""/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库库房"
                                   prop="storageName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="接收库房"
                                   prop="receiverIdName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库日期"
                                   prop="exportDate" width="100">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.exportDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'left'" :show-overflow-tooltip="true" label="操作人"
                                   prop="createByName" width="60px"/>
                  <el-table-column :align="'left'" :show-overflow-tooltip="true" label="已付款(元)"
                                   min-width="95px" prop="accountPayed">
                    <template #default="scope">
                      {{ parseFloat(scope.row.accountPayed).toFixed(2) }}
                    </template>
                  </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                            v-model:page="queryParams.pageNum" :total="total" @pagination="getList"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="14">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>出库单明细</span>
            </div>
            <div class="mb20">
              <el-table v-adaptive="50" :border="true" :data="stagingListDetail"
                          :header-cell-style="$headerCellStyle" height="400">
                  <el-table-column :align="'center'" label="药品编号" min-width="100px" prop="drugCode"/>
                  <el-table-column :align="'center'" label="药品名称" min-width="130px" prop="drugName"/>
                  <el-table-column :align="'center'" label="包装数量" min-width="90px"
                                   prop="packageNum"/>
                  <el-table-column :align="'center'" label="包装规格" min-width="120px"
                                   prop="packageSpec">
                    <template #default="scope">
                      {{ scope.row.packSize === '2' ? scope.row.packageSpec : scope.row.minSpec }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="出库数量" min-width="90px" prop="quantity">
                    <template #default="scope">
                      <div>
                        <dict-data-tag v-if="scope.row.packSize === '2'"
                                       :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                                       class="mb-10 mr10" style="float: right"/>
                        <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                       :value="scope.row.minUnits" class="mb-10 mr10"
                                       style="float: right"/>
                        <div class="mr20" style="float: right; font-weight: bold">
                          {{
                            scope.row.quantity
                          }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="进货价(元)" min-width="90px"
                                   prop="tradePrice">
                    <template #default="scope">
                      {{
                        scope.row.packSize === '2' ? scope.row.purchasePrice :
                          scope.row.tradePriceMin
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="零售价(元)" min-width="90px"
                                   prop="retailPrice">
                    <template #default="scope">
                      {{
                        scope.row.packSize === '2' ? scope.row.retailPrice :
                          scope.row.retailPriceMin
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="生产批号" min-width="90px" prop="batchNo"/>
                  <el-table-column :align="'center'" label="生产日期" min-width="90px" prop="produceDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="有效期" min-width="90px" prop="expireDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注" min-width="90px"
                                   prop="remarks"/>
                </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>

    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {quantityNumber, retailPriceV, tradePriceV} from "@/utils/myRules";
import {getStoreroomDistinguish} from "@/api/drug/drugInoutClass";
import {drugExportList, jsonStrInObj} from "@/utils/autoComplete";
import {autoExportList} from "@/api/drug/drugStock";
import {addDrugExportMaster, delDrugExportMaster, selectPageDrugExportMaster} from "@/api/drug/drugExportMaster.ts";
import {listDrugExportDetail} from "@/api/drug/drugExportDetail.ts";

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData("drug_storage_type", "drug_payment_type", "price_ratio", "spec_unit")
);
const formRef = ref()
const receiverIdDeptRef = ref()
// 科室等级字符串
const drugFromLevelStr = ref<String>('')
// 默认接收科室id
const defaultReceiverIdValue = ref("")
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const {proxy} = getCurrentInstance() as any
const currentSelectDept = proxy.$currentSelectDept
const itemAutomatic = ref()
// 项目选择自动补全窗体名称
const itemTitle = ref("药品选择");
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(drugExportList));
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([]);
// 项目选择自动补全字典数组
const dictArray = ref(["spec_unit"]);
// 出库方式list
const typeList = ref<any>([]);
const queryParams = ref<any>({})
// 进价合计
const tradePriceTotal = ref(0);
// 零售价合计
const retailPriceTotal = ref(0);
const rules = ref({
  tradePrice: [{required: true, validator: tradePriceV, trigger: "blur"}],
  retailPrice: [{required: true, validator: retailPriceV, trigger: "blur"}],
  produceDate: [{required: true, message: "生产日期不能为空", trigger: "blur"}],
  expireDate: [{required: true, message: "有效期不能为空", trigger: "blur"}],
  batchNo: [{required: true, message: "批号不能为空", trigger: "blur"}],
  exportClass: [{required: true, message: "出库方式不能为空", trigger: "change"}],
  discount: [{required: true, message: "比例不能为空", trigger: "change"}],
  receiverId: [{required: true, message: "接收科室不能为空", trigger: "blur"}],
  quantity: [{required: true, validator: quantityNumber, trigger: "blur"}],
});
// 表单参数
const form = ref<any>({
  exportClass: "",
  accountType: "1",
  isStaging: "N",
  exportStatus: "0",
  detailList: [
    {
      expireDate: "",
      discount: "1",
      itemInfo: "",
      infoId: "",
      drugName: "",
      drugCode: "",
      orgId: "",
      packageSpec: "",
      packageUnits: "",
      tradePrice: "",
      retailPrice: "",
      firmId: "",
      firmName: "",
      packageNum: "",
      drugPriceId: "",
    },
  ],
  detailListSave: [],
});
const receiverSupplierRef = ref()
const buttonLoading = ref(false);
const open = ref(false)
// 撤销列表
const stagingList = ref<any>([]);
// 撤销入库明细列表
const stagingListDetail = ref<any>([]);
// 总条数
const total = ref(0);
// 撤销列表查询参数
const detailQuery = ref<any>({
  pageNum: 1,
  pageSize: 10,
  masterId: "",
});

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
}
if (!currentSelectDept) {
  ElMessage.error("请选择库存药房后，再进行出库操作。");
} else {
  form.value.storageId = currentSelectDept;
}


// 监控科室是否改变，并查询出库方式
watch(() => proxy.$currentSelectDept, () => {
  getStoreroomDistinguishFun()
  form.value.storageId = currentSelectDept

}, {deep: true, immediate: true})

/** 根据科室id 出库类型获取库房对应的出出库方式 */
function getStoreroomDistinguishFun() {
  if (currentSelectDept) {
    typeList.value = [];
    let param = {
      storageCode: currentSelectDept,
      orgId: queryParams.value.orgId,
      inoutType: "2",
      dictType: "drug_storage_type",
    };
    getStoreroomDistinguish(param).then((res: any) => {
      res.data.forEach((item: any) => {
        item.sysDictData.fromLevel = item.fromLevel
        typeList.value.push(item.sysDictData);
      });
    });
  }
}
function exportClassClick(value: string) {
  defaultReceiverIdValue.value = "";
  form.value.receiverId = "";
  const index = typeList.value.findIndex((item: any) => {
    return item.dictValue == value;
  });
  if (index > -1) {
    drugFromLevelStr.value = typeList.value[index].fromLevel + ","
  }
}

/** 科室树选择事件 */
function storageIdClick(obj) {
  form.value.storageId = obj.id;
}

// 接收科室选择事件
function receiverIdClick(obj) {
  form.value.receiverId = obj.storageId;
  form.value.receiverSupplier = "";
}

/** 添加按钮操作 */
function handleAdd() {
  if (!form.value.exportClass) {
    return ElMessage.error("出库方式不能为空");
  }
  if (!form.value.storageId) {
    return ElMessage.error("供货单位不能为空");
  }
  if (form.value.exportClass === "8" && !form.value.receiverSupplier) {
    return ElMessage.error("退货单位不能为空");
  }
  if (form.value.exportClass !== "8" && form.value.exportClass !== "9" && !form.value.receiverId) {
    return ElMessage.error("接收科室不能为空");
  }

  const row = form.value.detailList[0]
  /** 出库数量校验 */
  if (row.quantity > row.quantityAll) {
    return ElMessage.error("出库数量不能多于现有库存数量，请重新输入")
  }
  // form.detailList.push({discount: '1', retailPrice: ''})
  (formRef.value as any).validate((valid) => {
    if (valid) {
      // 添加到已编辑列表
      form.value.detailListSave.push(form.value.detailList[0]);
      // 删除当前编辑列表数据
      form.value.detailList = [{expireDate: "", discount: "1"}];
      nextTick(() => {
        itemAutomatic.value.setItemName("");
      });
      computeSum();
    }
  });
  tableBodyList.value = [];
}

/** 已开药品明细计算合计 */
function computeSum() {
  // 进价合计
  let tradePriceTotalThis: number = 0;
  // 零售价合计
  let retailPriceTotalThis: number = 0;
  form.value.detailListSave.forEach((item: any) => {
    let quantity = item.quantity;
    tradePriceTotalThis += Number(item.tradePrice) * quantity;
    retailPriceTotalThis += Number(item.retailPrice) * quantity;
  });
  // 进价合计
  tradePriceTotal.value = Number(tradePriceTotalThis.toFixed(2));
  // 零售价合计
  retailPriceTotal.value = Number(retailPriceTotalThis.toFixed(2));
}

// 查询出库药品字典
function autoExportListFun() {
  const data = {
    orgId: queryParams.value.orgId,
    storageId: form.value.storageId,
    itemInfo: form.value.itemName
  }
  autoExportList(data).then((res: resType) => {
    tableBodyList.value = res.data;
    itemAutomatic.value.init();
  })
}

/**
 * 自动补全上边input获得焦点事件   待测试
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(row.drugName)
    itemAutomatic.value.focusInput()
  })
}

/** 药品自动补全点击事件 */
function rowClick(obj, index) {
  nextTick(() => {
    if (obj) {
      form.value.detailList[index].isShow = true
      form.value.detailList[index].itemInfo = obj.drugName;
      form.value.detailList[index].infoId = obj.drugInfoId;
      form.value.detailList[index].drugName = obj.drugName;
      form.value.detailList[index].drugCode = obj.drugCode;
      form.value.detailList[index].orgId = obj.orgId;
      form.value.detailList[index].packageSpec = obj.packageSpec;
      form.value.detailList[index].packageUnits = obj.packageUnits;
      form.value.detailList[index].packageSpec = obj.packageSpec;
      form.value.detailList[index].minSpec = obj.minSpec;
      form.value.detailList[index].minUnits = obj.minUnits;
      // 零售价
      form.value.detailList[index].retailPrice = obj.retailPrice;
      form.value.detailList[index].discount = "1";
      form.value.detailList[index].firmId = obj.firmId;
      form.value.detailList[index].firmName = obj.firmName;
      form.value.detailList[index].packageNum = obj.packageNum;
      form.value.detailList[index].drugPriceId = obj.drugPriceId;
      form.value.detailList[index].expireDate = obj.expireDate;
      form.value.detailList[index].produceDate = obj.produceDate;
      form.value.detailList[index].tradePrice = obj.tradePrice;
      form.value.detailList[index].batchNo = obj.batchNo;
      form.value.detailList[index].quantityAll = obj.quantity;
      form.value.detailList[index].packSize = obj.packSize;
      form.value.detailList[index].stockId = obj.stockId;
      form.value.detailList[index].currentSpec = obj.currentSpec
      form.value.detailList[index].currentUnits = obj.currentUnits
      form.value.detailList[index].drugInfoId = obj.drugInfoId
      itemAutomatic.value.closePopover();
      itemAutomatic.value.itemNameFocus();
    }
  });
}

/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  form.value.itemName = event;
  autoExportListFun();
}

/** 暂存 */
function temporaryStorage() {
  form.value.isStaging = "Y";
  save();
}

/** 最终提交 */
function lastSave() {
  form.value.isStaging = "N";
  save();
}

function save() {
  if (form.value.detailListSave.length <= 0) {
    return ElMessage.error("没有需要出库的药品明细，不能提交");
  }
  ElMessageBox.confirm(
    `${form.value.isStaging === "Y" ? "确认要进行暂存吗？" : "确认要进行出库吗？"}`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    form.value.orgId = queryParams.value.orgId;
    form.value.accountReceivable = tradePriceTotal.value;
    form.value.accountPayed = tradePriceTotal.value;
    if (form.value.exportClass === "9") {
      form.value.receiverId = form.value.storageId;
    }
    if (form.value.exportClass === "8") {
      form.value.receiverId = form.value.receiverSupplier;
    }
    let i = 0;
    form.value.detailListSave.forEach((item: any) => {
      i++;
      item.produceDate = proxy.$parseTime(item.produceDate, "{y}-{m}-{d} {h}:{i}:{s}");
      item.expireDate = proxy.$parseTime(item.expireDate, "{y}-{m}-{d} {h}:{i}:{s}");
      item.itemNo = i;
    });
    addDrugExportMaster(form.value).then(() => {
      if (form.value.isStaging === "Y") {
        ElMessage.success("暂存成功");
      } else {
        ElMessage.success("出库成功");
      }
      retailPriceTotal.value = 0.00
      tradePriceTotal.value = 0.00
      form.value.detailListSave = [];
      form.value.exportStatus = '0';
      form.value.exportId = '';
    }).finally(() => {
    });
  }).catch(() => {
    ElMessage.info("已取消操作");
  });
}

/** 修改按钮操作 */
function handleUpdate(row, index) {
  if (form.value.detailList[0].itemInfo) {
    ElMessageBox.confirm(
      "编辑列表存在未保存的药品数据，继续编辑将会替换编辑列表中的数据，确定要继续嘛？",
      "提示",
      {
        confirmButtonText: "替换编辑",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        form.value.detailList = [{expireDate: "", discount: "1"}];
        form.value.detailList[0] = row;
        form.value.detailListSave.splice(index, 1);
        nextTick(() => {
          itemAutomatic.value.setItemName(row.drugName);
        });
      })
      .catch(() => {
      });
  } else {
    form.value.detailList = [{expireDate: "", discount: "1"}];
    form.value.detailList[0] = row;
    form.value.detailListSave.splice(index, 1);
    nextTick(() => {
      itemAutomatic.value.setItemName(row.drugName);
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row, index) {
  // const ids = row.id || ids;
  ElMessageBox.confirm('是否确认删除药品"' + row.drugName + '"的数据？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      form.value.detailListSave.splice(index, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {
    });
}

/** 退货单位选择事件 */
function receiverSupplierChange(obj: any) {
  form.value.receiverSupplier = obj.id;
  form.value.receiverId = undefined;
}

/** 撤销列表弹出框 */
function temporaryStorageTableClick() {
  open.value = true;
  getList();
}

function temporaryStorageClose() {
  // 撤销列表
  stagingList.value = [];
  // 撤销明细列表
  stagingListDetail.value = [];
  open.value = false;
}

/** 查询药品撤销列表 */
function getList() {
  queryParams.value.storageId = form.value.storageId;
  queryParams.value.exportStatus = "1";
  // 只查询发放 调拨业务k
  queryParams.value.exportClassList = "6,7,12";
  selectPageDrugExportMaster(queryParams.value).then((response: any) => {
    stagingList.value = response.rows;
    total.value = response.total;
  });
}

async function getListDetail() {
  await listDrugExportDetail(detailQuery.value).then((response: any) => {
    stagingListDetail.value = response.data;
    stagingListDetail.value.forEach((item: any) => {
      item.tradePriceShow = item.packSize === "1" ? item.tradePriceMin : item.tradePrice;
      item.retailPriceShow = item.packSize === "1" ? item.retailPriceMin : item.retailPrice;
    })
  });
  return stagingListDetail.value;
}

/** 撤销列表主记录点击事件 */
async function stagingMaster(row, _index) {
  detailQuery.value.masterId = row.exportId;
  await getListDetail();
}

/**
 * 撤销列表 引入
 * @param row
 */
 async function bringIn(row) {
  if (form.value.detailListSave.length > 0) {
    return ElMessage.error("已添加列表存在未保存的数据，请出库后再引入当前数据");
  }
  detailQuery.value.masterId = row.exportId;
  let stagingListDetail = await getListDetail();
  form.value.exportClass = row.exportClass;
  form.value.accountType = row.accountType;
  form.value.invoiceNo = row.invoiceNo;
  form.value.documentNo = row.documentNo;
  form.value.exportId = row.exportId;
  form.value.exportStatus = '1';
  // 设置供货单位
  if (row.exportClass === "8") {
    nextTick(() => {
      exportClassClick(row.exportClass)
      receiverSupplierRef.value.setValue(row.receiverId);
      form.value.receiverSupplier = row.receiverSupplier;
      form.value.receiverId = undefined;
    });
  } else if (row.exportClass !== "9") {
    nextTick(() => {
      exportClassClick(row.exportClass)
      receiverIdDeptRef.value.setValue(row.receiverId);
      defaultReceiverIdValue.value = row.receiverId;
      form.value.receiverId = row.receiverId;
    });
  }
  // 设置出库明细
  stagingListDetail.forEach((obj) => {
    let detail: any = {};
    detail.itemInfo = obj.drugName;
    detail.id = obj.id;
    detail.drugInfoId = obj.drugInfoId;
    detail.masterId = obj.masterId;
    detail.drugName = obj.drugName;
    detail.drugCode = obj.drugCode;
    detail.orgId = obj.orgId;
    detail.packageSpec = obj.packageSpec;
    detail.currentSpec = obj.packageSpec;
    detail.packageUnits = obj.packageUnits;
    detail.currentUnits = obj.packSize === "1" ? obj.minUnits : obj.packageUnits;
    detail.minSpec = obj.minSpec;
    detail.minUnits = obj.minUnits;
    detail.tradePrice = obj.purchasePrice;
    detail.tradePriceMin = obj.tradePriceMin;
    detail.tradePriceShow = obj.packSize === "1" ? obj.tradePriceMin : obj.purchasePrice;
    detail.discount = obj.discount;
    detail.retailPrice = obj.retailPrice;
    detail.retailPriceMin = obj.retailPriceMin;
    detail.retailPriceShow = obj.packSize === "1" ? obj.retailPriceMin : obj.retailPrice;
    detail.packageNum = obj.packageNum;
    detail.drugPriceId = obj.drugPriceId;
    detail.packSize = obj.packSize;
    detail.quantity = obj.quantity;
    detail.produceDate = obj.produceDate;
    detail.expireDate = obj.expireDate;
    detail.batchNo = obj.batchNo;
    detail.location = obj.location;
    detail.firmName = obj.firmName;
    detail.firmId = obj.firmId;
    detail.drugPriceId = obj.priceId;
    detail.stockId = obj.stockId;
    form.value.detailListSave.push(detail);
  });
  computeSum();
  open.value = false;
}

function deleteMaster(row: any) {
  ElMessageBox.confirm('点击删除将会删除出库记录，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugExportMaster(row.exportId).then(() => {
      ElMessage.success("删除成功。");
      getList()
    })
  }).catch(() => {
    ElMessage.info("操作终止")
  })

}
</script>


<script lang="ts">
export default {
  name: "DrugExportMaster"
}
</script>

<style scoped>
:deep(.el-top) {
  background-color: rgb(212, 211, 211);
  border-radius: 5px 5px 5px 5px;
  margin: -5px 3px 5px 3px;
  height: 44px;
}

:deep(.dept-tree-label) {
  margin-right: -77px;
  margin-top: 6px;
  width: 18%;
}

:deep(.vue-treeselect__input-container) {
  height: 26px !important;
}

.account_type {
  font-weight: bold;
  color: rgb(30, 30, 30);
  float: left;
  width: 6%;
  /*margin-top: 6px;*/
}

:deep(.cell .el-tag) {
  margin: 0 -10px 0 -10px;
}

:deep(.el-input__wrapper) {
  background-color: #ff000017;
}
</style>
